﻿using Medallion.Threading;
using Microsoft.EntityFrameworkCore;
using Quartz;

namespace Application.Job
{
    public class CleanupLogsJob : IJob
    {
        private readonly JobManagerDbContext _dbContext;
        private readonly IDistributedLockProvider _synchronizationProvider;
        public CleanupLogsJob(JobManagerDbContext dbContext, IDistributedLockProvider synchronizationProvider)
        {
            _dbContext = dbContext;
            _synchronizationProvider = synchronizationProvider;
        }
        public async Task Execute(IJobExecutionContext context)
        {
            using (this._synchronizationProvider.AcquireLock($"UserAccount{Resource.CleanupLog}"))
            {
                var tasks = await _dbContext.JobTask.ToListAsync();
                foreach (var task in tasks)
                {
                    var time = DateTime.Now.AddDays(-task.LogRetentionDays);
                    var logs = await _dbContext.JobTaskRecord.Where(s => s.CreateTime < time).ToListAsync();
                    _dbContext.RemoveRange(logs);
                    var notices = await _dbContext.Notice.Where(s => s.CreateTime < time).ToListAsync();
                    _dbContext.RemoveRange(notices);
                }
                _dbContext.SaveChanges();
            }
        }
    }
}
